const logger = require('../logger');
const db = require('../../db');

class InfoType {
    /*
    constructor() {

    }
    */

    /**
     * 资讯类型列表
     */
    getInfoTypeList(req) {
        let info_type_id = '';
        let condition = {};
        if (req.params) {
            info_type_id = req.params.info_type_id;
            if (info_type_id) {
                condition = { info_type_id };
            }
        }
        logger.data.info('model.infoType.getInfoTypeList req：', req.params);
        return new Promise(function (resolve, reject) {
            // let condition = {};
            db.info_type.findAndCountAll({
                // attributes: [],
                where: condition,
                order: [
                    ['update_time', 'desc']
                ],
            }).then(function (result) {
                resolve(result);
            }, function (err) {
                logger.error.error('model.infoType.getInfoTypeList error：', err);
                reject(err);
            });
        });
    }

    /**
     * 保存资讯类型
     */
    saveInfoType(req) {
        let reqData = req.body;
        let { info_type_id } = reqData;
        const now = new Date();
        const uid = req.userInfo.uid;
        logger.data.info('model.infoType.saveInfoType req：', reqData);
        return new Promise(function (resolve, reject) {
            reqData.update_time = now;
            // 修改
            if (Number(info_type_id)) {
                reqData.updator = uid;
                logger.data.info('model.infoType.saveInfoType update：', reqData);
                db.info_type.update(reqData, {
                    where: { info_type_id }
                }).then(result => {
                    resolve(result[0]);
                }).catch(e => {
                    logger.error.error('model.infoType.saveInfoType update error：', e);
                    resolve('');
                });
            } else { // 新增
                reqData.creat_time = now;
                reqData.creator = uid;
                logger.data.info('model.infoType.saveInfoType create：', reqData);
                db.info_type.create(reqData).then(result => {
                    resolve(result);
                }).catch(e => {
                    logger.error.error('model.infoType.saveInfoType create error：', e);
                    resolve('');
                });
            }
        });
    }
}


module.exports = new InfoType();
